/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrn.engcomp.mpc.domain;

import br.ufrn.dca.controle.QuanserClient;
import br.ufrn.dca.controle.QuanserClientException;
import br.ufrn.engcomp.mpc.Constants;
import br.ufrn.engcomp.mpc.domain.exceptions.PlantCommunicationException;

/**
 *
 * @author Victor
 */
public class CoupledTanksPlant extends AbstractCoupledTanksPlant {
    
    // Cliente de comunicação
    private QuanserClient quanserClient;

    public CoupledTanksPlant() {
        super();

        inputOP = new double[] { 1.3284 };
        stateOP = new double[] { 15, 15 };

    }

    @Override
    public void connect(String ip, int port) throws PlantCommunicationException {
        try {
            quanserClient = new QuanserClient(ip, port);
        } catch (QuanserClientException qcex) {
            throw new PlantCommunicationException(qcex);
        }
    }

    @Override
    public void shutdown() throws PlantCommunicationException {
        try {
            if (quanserClient != null) {
                quanserClient.write(Constants.INPUT_PORT, 0.0);
            } else {
                throw new PlantCommunicationException("Not connected to the Plant.");
            }
        } catch (QuanserClientException qcex) {
            throw new PlantCommunicationException(qcex);
        }
    }

    @Override
    public void applyInput(double u) throws PlantCommunicationException {
        try {
            if (quanserClient != null) {
                quanserClient.write(Constants.INPUT_PORT, u);
            } else {
                throw new PlantCommunicationException("Not connected to the Plant.");
            }
        } catch (QuanserClientException qcex) {
            throw new PlantCommunicationException(qcex);
        }
    }

    @Override
    public double[] readOutput() throws PlantCommunicationException {
        try {
            if (quanserClient != null) {
                double[] output = new double[Constants.N];

                output[0] = quanserClient.read(Constants.OUTPUT_PORT_1) * Constants.CTE_TANQUE;
                output[1] = quanserClient.read(Constants.OUTPUT_PORT_2) * Constants.CTE_TANQUE;

                return output;
            } else {
                throw new PlantCommunicationException("Not connected to the Plant.");
            }
        } catch (QuanserClientException qcex) {
            throw new PlantCommunicationException(qcex);
        }
    }

    @Override
    public String getCodeName() {
        return "NLP";
    }
    
}
